<?php
namespace Tbf\Component\Strings;
class StringFunction
{
    /**
     * 在一个字符串里面另一个字符串出现的第n个位置
      @param 长字符串 $str
      @param 段字符串 $needles
      @param 第n个位置 $n
     */
    public static function nthPos ($str, $needles, $n=1)
    {
        //    finds the nth occurrence of any of $needles' characters in $str
        //  returns -1 if not found; $n<0 => count backwards from end
        //  e.g. $str = "c:\\winapps\\morph\\photos\\Party\\Phoebe.jpg";
        //       substr($str, nthPos($str, "/\\:", -2)) => \Party\Phoebe.jpg
        //       substr($str, nthPos($str, "/\\:", 4)) => \photos\Party\Phoebe.jpg
        $pos = -1;
        $size = strlen($str);
        if ($reverse=($n<0)) {
            $n=-$n; $str = strrev($str);
        }
        while ($n--) {
            $bestNewPos = $size;
            for ($i=strlen($needles)-1;$i>=0;$i--) {
                $newPos = strpos($str, $needles[$i], $pos+1);
                if ($newPos===false) $needles = substr($needles,0,$i) . substr($needles,$i+1);
                else $bestNewPos = min($bestNewPos,$newPos);
            }
            if (($pos=$bestNewPos)==$size) return -1;
        }

        return $reverse ? $size-1-$pos : $pos;
    }
    /**
     * 字符串是否以xxx开头
     */
    public static function startWith($str,$needles)
    {
        return substr($str,0,strlen($needles)) === $needles;
    }
    /**
     * 从字符串开头移除xxx
     * 如果字符串不存在,则返回$str
     */
    public static function removeFromStart($str,$needles)
    {
        if (!self::startWith($str, $needles)) {
            return false;
        }

        return substr($str,strlen($needles));
    }
    /**
     * 字符串以xxx结束
      @param $haystack
      @param $needle
      @return boolean
     */
    public static function endWith($haystack, $needle)
    {
        $length = strlen($needle);
        if ($length == 0) {
            return true;
        }

        return (substr($haystack, -$length) === $needle);
    }
    /**
     * 从字符串结尾移除xxx
     */
    public static function removeFromEnd($str,$needles)
    {
        if (!self::endWith($str, $needles)) {
            return false;
        }

        return substr($str,0,-strlen($needles));
    }
}
